﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace SimpleDatabaseAdapter
{
    internal class Propertyes
    {
        private static readonly Type _AllDataItemAttribute = typeof(AllDataItemAttribute);

        public static PropertyInfo[] GetPropertyes(Type type)
        {
            return type.GetProperties();
        }
        public static PropertyInfo[] GetPropertyesNoBase(Type type)
        {
            return type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
        }
        public static PropertyInfo[] GetAllDataItemPropertyes(Type type)
        {
            PropertyInfo[] allPropertyes = GetPropertyes(type);
            return GetPropertyesWithAttribute(allPropertyes, _AllDataItemAttribute);
        }
        public static PropertyInfo[] GetAllDataItemPropertyesNoBase(Type type)
        {
            PropertyInfo[] allPropertyes = GetPropertyesNoBase(type);
            return GetPropertyesWithAttribute(allPropertyes, _AllDataItemAttribute);
        }
        public static PropertyInfo[] GetPropertyesWithAttribute(PropertyInfo[] allPropertyes, Type attrType)
        {
            List<PropertyInfo> truePropertyes = new List<PropertyInfo>();

            foreach (PropertyInfo property in allPropertyes)
            {
                if (property.IsDefined(attrType, true))
                {
                    truePropertyes.Add(property);
                }
            }

            return truePropertyes.ToArray();
        }
        public static AllDataItemAttribute[] GetAllDataItemAttributes(Type type)
        {
            PropertyInfo[] propertyes = GetPropertyes(type);
            return GetAttributes(propertyes);
        }
        public static AllDataItemAttribute[] GetAllDataItemAttributesNoBase(Type type)
        {
            PropertyInfo[] propertyes = GetPropertyesNoBase(type);
            return GetAttributes(propertyes);
        }
        public static AllDataItemAttribute[] GetAttributes(PropertyInfo[] allPropertyes)
        {
            List<AllDataItemAttribute> attributes = new List<AllDataItemAttribute>();

            foreach (PropertyInfo property in allPropertyes)
            {
                if (property.IsDefined(_AllDataItemAttribute, true))
                {
                    attributes.Add(property.GetCustomAttribute(_AllDataItemAttribute) as AllDataItemAttribute);
                }
            }

            return attributes.ToArray();
        }       
    }
}
